<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta name="baidu-site-verification" content="UqlC4pwKIm" />
  <meta name="baidu-site-verification" content="d3U0dGeqGw" />
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="1C1XSuJ8TgM2O0mcZvsgzEdy0IdRZOJfxDYPyh18U9Q" />














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.cat.net/css?family=Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="ML,python3,SVM," />





  <link rel="alternate" href="/atom.xml" title="WordZzzz" type="application/atom+xml" />






<meta name="description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 代码地址：https://github.com/WordZzzz/ML/tree/master/Ch06 操作系统：WINDOWS 10 软件版本：python-3.6.2-amd64 编&amp;emsp;&amp;emsp;者：WordZzzz   前言：&amp;emsp;&amp;emsp;前面三篇讲的都是SVM线性分类器，如果数">
<meta name="keywords" content="ML,python3,SVM">
<meta property="og:type" content="article">
<meta property="og:title" content="《机器学习实战》之支持向量机（4）核函数及其实现">
<meta property="og:url" content="http://wordzzzz.gitee.io/2017/11/05/ml-17/index.html">
<meta property="og:site_name" content="WordZzzz">
<meta property="og:description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 代码地址：https://github.com/WordZzzz/ML/tree/master/Ch06 操作系统：WINDOWS 10 软件版本：python-3.6.2-amd64 编&amp;emsp;&amp;emsp;者：WordZzzz   前言：&amp;emsp;&amp;emsp;前面三篇讲的都是SVM线性分类器，如果数">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20171009221829629?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171009221909966?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171009221934280?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2018-01-01T12:15:33.446Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《机器学习实战》之支持向量机（4）核函数及其实现">
<meta name="twitter:description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 代码地址：https://github.com/WordZzzz/ML/tree/master/Ch06 操作系统：WINDOWS 10 软件版本：python-3.6.2-amd64 编&amp;emsp;&amp;emsp;者：WordZzzz   前言：&amp;emsp;&amp;emsp;前面三篇讲的都是SVM线性分类器，如果数">
<meta name="twitter:image" content="http://img.blog.csdn.net/20171009221829629?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://wordzzzz.gitee.io/2017/11/05/ml-17/"/>





  <title>《机器学习实战》之支持向量机（4）核函数及其实现 | WordZzzz</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-111723881-1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?38fde15c2737a3b69622e9dd4f67f6f1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">WordZzzz</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">My Awesome Site</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://wordzzzz.gitee.io/2017/11/05/ml-17/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Word Zzzz">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WordZzzz">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">《机器学习实战》之支持向量机（4）核函数及其实现</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-05T00:00:00+08:00">
                2017-11-05
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-01-01T20:15:33+08:00">
                2018-01-01
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习实战/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习实战</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/11/05/ml-17/" class="leancloud_visitors" data-flag-title="《机器学习实战》之支持向量机（4）核函数及其实现">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5,154
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  23
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><hr>
<ul>
<li><strong>转载请注明作者和出处：<a href="http://blog.csdn.net/u011475210" target="_blank" rel="noopener">http://blog.csdn.net/u011475210</a></strong></li>
<li><strong>代码地址：<a href="https://github.com/WordZzzz/ML/tree/master/Ch06" target="_blank" rel="noopener">https://github.com/WordZzzz/ML/tree/master/Ch06</a></strong></li>
<li><strong>操作系统：WINDOWS 10</strong></li>
<li><strong>软件版本：python-3.6.2-amd64</strong></li>
<li><strong>编&emsp;&emsp;者：WordZzzz</strong></li>
</ul>
<hr>
<h2 id="前言："><a href="#前言：" class="headerlink" title="前言："></a>前言：</h2><p>&emsp;&emsp;前面三篇讲的都是SVM线性分类器，如果数据集非线性可分（如下图所示），那就需要做些修改了。</p>
<p></p><br><div align="center"><img src="http://img.blog.csdn.net/20171009221829629?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast"></div><br><p></p>

<p>&emsp;&emsp;显而易见，在该数据中存在某种可以识别的模式。接下来，我们就需要使用一种称为核函数（kernel）的工具将数据转换成易于分类器理解的形式。在本篇博文中，我们先对核函数进行简单的了解，然后重点研究径向基函数（radial basis function，最流行的核函数）及其实现，最后在我们之前的手写数字识别问题上进行实践。</p>
<h2 id="核函数简介"><a href="#核函数简介" class="headerlink" title="核函数简介"></a>核函数简介</h2><p>&emsp;&emsp;再看本文章开头的图片，我们似乎可以用一个圆来吧数据划分开来，但是对于线性分类器来说，这好像很难实现。我们或许可以对数据进行某种形式的转换，从而得到某些新的变量来表示数据。在这个例子中，我们将数据从一个特征空间转换到另一个特征空间，在新空间下，我们可以很容易利用已有的工具对数据进行处理。这个过程，学过数学的都知道，即从一个特征空间到另一个特征空间的映射。通常情况下，核函数实现的是低维到高维的映射，以后其他算法涉及到的PCA等，则是高维到低微的映射。经过空间转换之后，我们可以在高维空间解决线性问题，这也就等价于在低维空间中解决非线性问题。</p>
<p>&emsp;&emsp;SVM优化中一个特别好的地方就是，所有的运算都可以写成内积（inner product，也叫点积）的形式。向量的内积指的是两个向量相乘，之后得到单个标量或者数值。我们可以把内积运算替换成核函数，而不必做简化处理。将内积替换成核函数的方式被称为核技巧（kernel trick）或者核“变电”（kernel substation）。</p>
<p>&emsp;&emsp;当然，核函数并不仅仅应用于SVM中，很多其他的机器学习算法也都用到核函数。接下来，我们就来介绍一个流行的核函数，那就是径向基函数。</p>
<h2 id="径向基函数"><a href="#径向基函数" class="headerlink" title="径向基函数"></a>径向基函数</h2><p>&emsp;&emsp;径向基函数是一个采用向量作为自变量的函数，能够基于向量距离运算输出一个标量。这个距离可以使从<0,0>向量或者其他向量开始计算的距离。我们用到的径向基函数的高斯版本公式为：</0,0></p>
<p>$$<br>k(x,y) = exp(\frac{ {-\begin{Vmatrix} x-y \end{Vmatrix} }^2}{2 \sigma^2})<br>$$</p>
<p>&emsp;&emsp;其中，σ是用户定义的用于确定到达率（reach）或者说是函数值跌落到0的速度参数。</p>
<p>&emsp;&emsp;上述高斯核函数将数据从其特征空间映射到跟高维的空间，具体来说这里是映射到一个无穷维的空间。在该数据集上，使用高斯核函数得到一个很好的结果，当然，该函数也可以用于许多其他的数据集，并且也能够得到低错误率的结果。</p>
<h2 id="核函数实现"><a href="#核函数实现" class="headerlink" title="核函数实现"></a>核函数实现</h2><p>&emsp;&emsp;如果在svmMLiA.py文件中添加一个函数并稍作修改，那么我们就能在已有代码中使用核函数了（所有与核函数实现相关的函数，函数名末尾都是K）。其中主要区分代码在innerLK()和calcEk()中，我已经重点标记出。</p>
<p>&emsp;&emsp;新添加的核转换函数，主要用于填充结构体和后续的计算：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">kernelTrans</span><span class="params">(X, A, kTup)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	核转换函数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		X：数据集</span></span><br><span class="line"><span class="string">				A：某一行数据</span></span><br><span class="line"><span class="string">				kTup：核函数信息</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	K：计算出的核向量</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#获取数据集行列数</span></span><br><span class="line">	m, n = shape(X)</span><br><span class="line">	<span class="comment">#初始化列向量</span></span><br><span class="line">	K = mat(zeros((m, <span class="number">1</span>)))</span><br><span class="line">	<span class="comment">#根据键值选择相应核函数</span></span><br><span class="line">	<span class="comment">#lin表示的是线性核函数</span></span><br><span class="line">	<span class="keyword">if</span> kTup[<span class="number">0</span>] == <span class="string">'lin'</span>: K = X * A.T</span><br><span class="line">	<span class="comment">#rbf表示径向基核函数</span></span><br><span class="line">	<span class="keyword">elif</span> kTup[<span class="number">0</span>] == <span class="string">'rbf'</span>:</span><br><span class="line">		<span class="keyword">for</span> j <span class="keyword">in</span> range(m):</span><br><span class="line">			deltaRow = X[j,:] - A</span><br><span class="line">			K[j] = deltaRow * deltaRow.T</span><br><span class="line">		<span class="comment">#对矩阵元素展开计算，而不像在MATLAB中一样计算矩阵的逆</span></span><br><span class="line">		K =  exp(K/(<span class="number">-1</span>*kTup[<span class="number">1</span>]**<span class="number">2</span>))</span><br><span class="line">	<span class="comment">#如果无法识别，就报错</span></span><br><span class="line">	<span class="keyword">else</span>: <span class="keyword">raise</span> NameError(<span class="string">'Houston We Have a Problem -- That Kernel is not recognized'</span>)</span><br><span class="line">	<span class="comment">#返回计算出的核向量</span></span><br><span class="line">	<span class="keyword">return</span> K</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;其他函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">optStructK</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	存放运算中重要的值</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		dataMatIn：数据集</span></span><br><span class="line"><span class="string">				classLabels：类别标签</span></span><br><span class="line"><span class="string">				C：常数C</span></span><br><span class="line"><span class="string">				toler：容错率</span></span><br><span class="line"><span class="string">				kTup：速度参数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	X：数据集</span></span><br><span class="line"><span class="string">				labelMat：类别标签</span></span><br><span class="line"><span class="string">				C：常数C</span></span><br><span class="line"><span class="string">				tol：容错率</span></span><br><span class="line"><span class="string">				m：数据集行数</span></span><br><span class="line"><span class="string">				b：常数项</span></span><br><span class="line"><span class="string">				alphas：alphas矩阵</span></span><br><span class="line"><span class="string">				eCache：误差缓存</span></span><br><span class="line"><span class="string">				K：核函数矩阵</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, dataMatIn, classLabels, C, toler, kTup)</span>:</span></span><br><span class="line">		self.X = dataMatIn</span><br><span class="line">		self.labelMat = classLabels</span><br><span class="line">		self.C = C</span><br><span class="line">		self.tol = toler</span><br><span class="line">		self.m = shape(dataMatIn)[<span class="number">0</span>]</span><br><span class="line">		self.alphas = mat(zeros((self.m, <span class="number">1</span>)))</span><br><span class="line">		self.b = <span class="number">0</span></span><br><span class="line">		self.eCache = mat(zeros((self.m, <span class="number">2</span>)))</span><br><span class="line">		</span><br><span class="line">		<span class="string">""" 主要区分 """</span></span><br><span class="line">		self.K = mat(zeros((self.m, self.m)))</span><br><span class="line">		<span class="keyword">for</span> i <span class="keyword">in</span> range(self.m):</span><br><span class="line">			self.K[:,i] = kernelTrans(self.X, self.X[i,:], kTup)</span><br><span class="line">		<span class="string">""" 主要区分 """</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">calcEkK</span><span class="params">(oS, k)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	计算误差值E</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		oS：数据结构</span></span><br><span class="line"><span class="string">				k：下标</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	Ek：计算的E值</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	</span><br><span class="line">	<span class="string">""" 主要区分 """</span></span><br><span class="line">	<span class="comment">#计算fXk，整个对应输出公式f(x)=w`x + b</span></span><br><span class="line">	<span class="comment">#fXk = float(multiply(oS.alphas, oS.labelMat).T * (oS.X * oS.X[k,:].T)) + oS.b</span></span><br><span class="line">	fXk = float(multiply(oS.alphas, oS.labelMat).T*oS.K[:, k] + oS.b)</span><br><span class="line">	<span class="string">""" 主要区分 """</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">#计算E值</span></span><br><span class="line">	Ek = fXk - float(oS.labelMat[k])</span><br><span class="line">	<span class="comment">#返回计算的误差值E</span></span><br><span class="line">	<span class="keyword">return</span> Ek</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">selectJK</span><span class="params">(i, oS, Ei)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	选择第二个alpha的值</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		i：第一个alpha的下标</span></span><br><span class="line"><span class="string">				oS：数据结构</span></span><br><span class="line"><span class="string">				Ei：计算出的第一个alpha的误差值</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	j：第二个alpha的下标</span></span><br><span class="line"><span class="string">				Ej：计算出的第二个alpha的误差值</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#初始化参数值</span></span><br><span class="line">	maxK = <span class="number">-1</span>; maxDeltaE = <span class="number">0</span>; Ej = <span class="number">0</span></span><br><span class="line">	<span class="comment">#构建误差缓存</span></span><br><span class="line">	oS.eCache[i] = [<span class="number">1</span>, Ei]</span><br><span class="line">	<span class="comment">#构建一个非零列表，返回值是第一个非零E所对应的alpha值，而不是E本身</span></span><br><span class="line">	validEcacheList = nonzero(oS.eCache[:, <span class="number">0</span>].A)[<span class="number">0</span>]</span><br><span class="line">	<span class="comment">#如果列表长度大于1，说明不是第一次循环</span></span><br><span class="line">	<span class="keyword">if</span> (len(validEcacheList)) &gt; <span class="number">1</span>:</span><br><span class="line">		<span class="comment">#遍历列表中所有元素</span></span><br><span class="line">		<span class="keyword">for</span> k <span class="keyword">in</span> validEcacheList:</span><br><span class="line">			<span class="comment">#如果是第一个alpha的下标，就跳出本次循环</span></span><br><span class="line">			<span class="keyword">if</span> k == i: <span class="keyword">continue</span></span><br><span class="line">			<span class="comment">#计算k下标对应的误差值</span></span><br><span class="line">			Ek = calcEkK(oS, k)</span><br><span class="line">			<span class="comment">#取两个alpha误差值的差值的绝对值</span></span><br><span class="line">			deltaE = abs(Ei - Ek)</span><br><span class="line">			<span class="comment">#最大值更新</span></span><br><span class="line">			<span class="keyword">if</span> (deltaE &gt; maxDeltaE):</span><br><span class="line">				maxK = k; maxDeltaE = deltaE; Ej = Ek</span><br><span class="line">		<span class="comment">#返回最大差值的下标maxK和误差值Ej</span></span><br><span class="line">		<span class="keyword">return</span> maxK, Ej</span><br><span class="line">	<span class="comment">#如果是第一次循环，则随机选择alpha，然后计算误差</span></span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		j = selectJrand(i, oS.m)</span><br><span class="line">		Ej = calcEkK(oS, j)</span><br><span class="line">	<span class="comment">#返回下标j和其对应的误差Ej</span></span><br><span class="line">	<span class="keyword">return</span> j, Ej</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">updateEkK</span><span class="params">(oS, k)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	更新误差缓存</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		oS：数据结构</span></span><br><span class="line"><span class="string">				j：alpha的下标</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	无</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#计算下表为k的参数的误差</span></span><br><span class="line">	Ek = calcEkK(oS, k)</span><br><span class="line">	<span class="comment">#将误差放入缓存</span></span><br><span class="line">	oS.eCache[k] = [<span class="number">1</span>, Ek]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">innerLK</span><span class="params">(i, oS)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	完整SMO算法中的优化例程</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		oS：数据结构</span></span><br><span class="line"><span class="string">				i：alpha的下标</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	无</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#计算误差</span></span><br><span class="line">	Ei = calcEkK(oS, i)</span><br><span class="line">	<span class="comment">#如果标签与误差相乘之后在容错范围之外，且超过各自对应的常数值，则进行优化</span></span><br><span class="line">	<span class="keyword">if</span> ((oS.labelMat[i]*Ei &lt; -oS.tol) <span class="keyword">and</span> (oS.alphas[i] &lt; oS.C)) <span class="keyword">or</span> ((oS.labelMat[i]*Ei &gt; oS.tol) <span class="keyword">and</span> (oS.alphas[i] &gt; <span class="number">0</span>)):</span><br><span class="line">		<span class="comment">#启发式选择第二个alpha值</span></span><br><span class="line">		j, Ej = selectJK(i, oS, Ei)</span><br><span class="line">		<span class="comment">#利用copy存储刚才的计算值，便于后期比较</span></span><br><span class="line">		alphaIold = oS.alphas[i].copy(); alpahJold = oS.alphas[j].copy();</span><br><span class="line">		<span class="comment">#保证alpha在0和C之间</span></span><br><span class="line">		<span class="keyword">if</span> (oS.labelMat[i] != oS.labelMat[j]):</span><br><span class="line">			L = max(<span class="number">0</span>, oS.alphas[j] - oS. alphas[i])</span><br><span class="line">			H = min(oS.C, oS.C + oS.alphas[j] - oS.alphas[i])</span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			L = max(<span class="number">0</span>, oS.alphas[j] + oS.alphas[i] - oS.C)</span><br><span class="line">			H = min(oS.C, oS.alphas[j] + oS.alphas[i])</span><br><span class="line">		<span class="comment">#如果界限值相同，则不做处理直接跳出本次循环</span></span><br><span class="line">		<span class="keyword">if</span> L == H: print(<span class="string">"L==H"</span>); <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">		</span><br><span class="line">		<span class="string">""" 主要区分 """</span></span><br><span class="line">		<span class="comment">#最优修改量，求两个向量的内积（核函数）</span></span><br><span class="line">		<span class="comment">#eta = 2.0 * oS.X[i, :]*oS.X[j, :].T - oS.X[i, :]*oS.X[i, :].T - oS.X[j, :]*oS.X[j, :].T</span></span><br><span class="line">		eta = <span class="number">2.0</span> * oS.K[i, j] - oS.K[i, i] - oS.K[j, j]</span><br><span class="line">		<span class="string">""" 主要区分 """</span></span><br><span class="line">		</span><br><span class="line">		<span class="comment">#如果最优修改量大于0，则不做处理直接跳出本次循环，这里对真实SMO做了简化处理</span></span><br><span class="line">		<span class="keyword">if</span> eta &gt;= <span class="number">0</span>: print(<span class="string">"eta&gt;=0"</span>); <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">		<span class="comment">#计算新的alphas[j]的值</span></span><br><span class="line">		oS.alphas[j] -= oS.labelMat[j]*(Ei - Ej)/eta</span><br><span class="line">		<span class="comment">#对新的alphas[j]进行阈值处理</span></span><br><span class="line">		oS.alphas[j] = clipAlpha(oS.alphas[j], H, L)</span><br><span class="line">		<span class="comment">#更新误差缓存</span></span><br><span class="line">		updateEkK(oS, j)</span><br><span class="line">		<span class="comment">#如果新旧值差很小，则不做处理跳出本次循环</span></span><br><span class="line">		<span class="keyword">if</span> (abs(oS.alphas[j] - alpahJold) &lt; <span class="number">0.00001</span>): print(<span class="string">"j not moving enough"</span>); <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">		<span class="comment">#对i进行修改，修改量相同，但是方向相反</span></span><br><span class="line">		oS.alphas[i] += oS.labelMat[j] * oS.labelMat[i] * (alpahJold - oS.alphas[j])</span><br><span class="line">		<span class="comment">#更新误差缓存</span></span><br><span class="line">		updateEkK(oS, i)</span><br><span class="line">		</span><br><span class="line">		<span class="string">""" 主要区分 """</span></span><br><span class="line">		<span class="comment">#更新常数项</span></span><br><span class="line">		<span class="comment">#b1 = oS.b - Ei - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.X[i, :]*oS.X[i, :].T - oS.labelMat[j] * (oS.alphas[j] - alpahJold) * oS.X[i, :]*oS.X[j, :].T</span></span><br><span class="line">		<span class="comment">#b2 = oS.b - Ej - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.X[i, :]*oS.X[j, :].T - oS.labelMat[j] * (oS.alphas[j] - alpahJold) * oS.X[j, :]*oS.X[j, :].T</span></span><br><span class="line">		b1 = oS.b - Ei - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.K[i, i] - oS.labelMat[j] * (oS.alphas[j] - alpahJold) * oS.K[i, j]</span><br><span class="line">		b2 = oS.b - Ej - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.K[i, j] - oS.labelMat[j] * (oS.alphas[j] - alpahJold) * oS.K[j, j]</span><br><span class="line">		<span class="string">""" 主要区分 """</span></span><br><span class="line">		</span><br><span class="line">		<span class="comment">#谁在0到C之间，就听谁的，否则就取平均值</span></span><br><span class="line">		<span class="keyword">if</span> (<span class="number">0</span> &lt; oS.alphas[i]) <span class="keyword">and</span> (oS.C &gt; oS.alphas[i]): oS.b = b1</span><br><span class="line">		<span class="keyword">elif</span> (<span class="number">0</span> &lt; oS.alphas[j]) <span class="keyword">and</span> (oS.C &gt; oS.alphas[i]): oS.b = b2</span><br><span class="line">		<span class="keyword">else</span>: oS.b = (b1 + b2) / <span class="number">2.0</span></span><br><span class="line">		<span class="comment">#成功返回1</span></span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">	<span class="comment">#失败返回0</span></span><br><span class="line">	<span class="keyword">else</span>: <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">smoPK</span><span class="params">(dataMatIn, classLabels, C, toler, maxIter, kTup = <span class="params">(<span class="string">'lin'</span>, <span class="number">0</span>)</span>)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	完整SMO算法</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		dataMatIn：数据集</span></span><br><span class="line"><span class="string">				classLabels：类别标签</span></span><br><span class="line"><span class="string">				C：常数C</span></span><br><span class="line"><span class="string">				toler：容错率</span></span><br><span class="line"><span class="string">				maxIter：最大的循环次数</span></span><br><span class="line"><span class="string">				kTup：速度参数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	b：常数项</span></span><br><span class="line"><span class="string">				alphas：数据向量</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#新建数据结构对象</span></span><br><span class="line">	oS = optStructK(mat(dataMatIn), mat(classLabels).transpose(), C, toler, kTup)</span><br><span class="line">	<span class="comment">#初始化迭代次数</span></span><br><span class="line">	iter = <span class="number">0</span></span><br><span class="line">	<span class="comment">#初始化标志位</span></span><br><span class="line">	entireSet = <span class="keyword">True</span>; alphaPairsChanged = <span class="number">0</span></span><br><span class="line">	<span class="comment">#终止条件：迭代次数超限、遍历整个集合都未对alpha进行修改</span></span><br><span class="line">	<span class="keyword">while</span> (iter &lt; maxIter) <span class="keyword">and</span> ((alphaPairsChanged &gt; <span class="number">0</span>) <span class="keyword">or</span> (entireSet)):</span><br><span class="line">		alphaPairsChanged = <span class="number">0</span></span><br><span class="line">		<span class="comment">#根据标志位选择不同的遍历方式</span></span><br><span class="line">		<span class="keyword">if</span> entireSet:</span><br><span class="line">			<span class="comment">#遍历任意可能的alpha值</span></span><br><span class="line">			<span class="keyword">for</span> i <span class="keyword">in</span> range(oS.m):</span><br><span class="line">				<span class="comment">#选择第二个alpha值，并在可能时对其进行优化处理</span></span><br><span class="line">				alphaPairsChanged += innerLK(i, oS)</span><br><span class="line">				print(<span class="string">"fullSet, iter: %d i: %d, pairs changed %d"</span> % (iter, i, alphaPairsChanged))</span><br><span class="line">			<span class="comment">#迭代次数累加</span></span><br><span class="line">			iter += <span class="number">1</span></span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			<span class="comment">#得出所有的非边界alpha值</span></span><br><span class="line">			nonBoundIs = nonzero((oS.alphas.A &gt; <span class="number">0</span>) * (oS.alphas.A &lt; C))[<span class="number">0</span>]</span><br><span class="line">			<span class="comment">#遍历所有的非边界alpha值</span></span><br><span class="line">			<span class="keyword">for</span> i <span class="keyword">in</span> nonBoundIs:</span><br><span class="line">				<span class="comment">#选择第二个alpha值，并在可能时对其进行优化处理</span></span><br><span class="line">				alphaPairsChanged += innerLK(i, oS)</span><br><span class="line">				print(<span class="string">"non-bound, iter: %d i: %d, pairs changed %d"</span> % (iter, i, alphaPairsChanged))</span><br><span class="line">			<span class="comment">#迭代次数累加</span></span><br><span class="line">			iter += <span class="number">1</span></span><br><span class="line">		<span class="comment">#在非边界循环和完整遍历之间进行切换</span></span><br><span class="line">		<span class="keyword">if</span> entireSet: entireSet = <span class="keyword">False</span></span><br><span class="line">		<span class="keyword">elif</span> (alphaPairsChanged == <span class="number">0</span>): entireSet =<span class="keyword">True</span></span><br><span class="line">		print(<span class="string">"iteration number: %d"</span> % iter)</span><br><span class="line">	<span class="comment">#返回常数项和数据向量</span></span><br><span class="line">	<span class="keyword">return</span> oS.b, oS.alphas</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;接下来我们写测试函数。整个代码中最重要的是for循环开始的那两行，他们给出了如何利用核函数进行分类。首先利用结构初始化方法中使用过的kernelTrans()函数，得到转换后的数据。然后，再用其与前面的alpha及类别标签值求积。特别需要注意观察的是，我们是如何做到只需要支持向量数据就可以进行分类的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">testRbf</span><span class="params">(k1 = <span class="number">1.3</span>)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	利用核函数进行分类的径向基测试函数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		k1：径向基函数的速度参数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	输出打印信息</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#导入数据集</span></span><br><span class="line">	dataArr, labelArr = loadDataSet(<span class="string">'testSetRBF.txt'</span>)</span><br><span class="line">	<span class="comment">#调用Platt SMO算法</span></span><br><span class="line">	b, alphas = smoPK(dataArr, labelArr, <span class="number">200</span>, <span class="number">0.00001</span>, <span class="number">10000</span>, (<span class="string">'rbf'</span>, k1))</span><br><span class="line">	<span class="comment">#初始化数据矩阵和标签向量</span></span><br><span class="line">	datMat = mat(dataArr); labelMat = mat(labelArr).transpose()</span><br><span class="line">	<span class="comment">#记录支持向量序号</span></span><br><span class="line">	svInd = nonzero(alphas.A &gt; <span class="number">0</span>)[<span class="number">0</span>]</span><br><span class="line">	<span class="comment">#读取支持向量</span></span><br><span class="line">	sVs = datMat[svInd]</span><br><span class="line">	<span class="comment">#读取支持向量对应标签</span></span><br><span class="line">	labelSV = labelMat[svInd]</span><br><span class="line">	<span class="comment">#输出打印信息</span></span><br><span class="line">	print(<span class="string">"there are %d Support Vectors"</span> % shape(sVs)[<span class="number">0</span>])</span><br><span class="line">	<span class="comment">#获取数据集行列值</span></span><br><span class="line">	m, n = shape(datMat)</span><br><span class="line">	<span class="comment">#初始化误差计数</span></span><br><span class="line">	errorCount = <span class="number">0</span></span><br><span class="line">	<span class="comment">#遍历每一行，利用核函数对训练集进行分类</span></span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> range(m):</span><br><span class="line">		<span class="comment">#利用核函数转换数据</span></span><br><span class="line">		kernelEval = kernelTrans(sVs, datMat[i,:], (<span class="string">'rbf'</span>, k1))</span><br><span class="line">		<span class="comment">#仅用支持向量预测分类</span></span><br><span class="line">		predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b</span><br><span class="line">		<span class="comment">#预测分类结果与标签不符则错误计数加一</span></span><br><span class="line">		<span class="keyword">if</span> sign(predict) != sign(labelArr[i]): errorCount += <span class="number">1</span></span><br><span class="line">	<span class="comment">#打印输出分类错误率</span></span><br><span class="line">	print(<span class="string">"the training error rate is: %f"</span> % (float(errorCount)/m))</span><br><span class="line">	<span class="comment">#导入测试数据集</span></span><br><span class="line">	dataArr, labelArr = loadDataSet(<span class="string">'testSetRBF2.txt'</span>)</span><br><span class="line">	<span class="comment">#初始化误差计数</span></span><br><span class="line">	errorCount = <span class="number">0</span></span><br><span class="line">	<span class="comment">#初始化数据矩阵和标签向量</span></span><br><span class="line">	datMat = mat(dataArr); labelMat = mat(labelArr).transpose()</span><br><span class="line">	<span class="comment">#获取数据集行列值</span></span><br><span class="line">	m, n = shape(datMat)</span><br><span class="line">	<span class="comment">#遍历每一行，利用核函数对测试集进行分类</span></span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> range(m):</span><br><span class="line">		<span class="comment">#利用核函数转换数据</span></span><br><span class="line">		kernelEval = kernelTrans(sVs, datMat[i,:], (<span class="string">'rbf'</span>, k1))</span><br><span class="line">		<span class="comment">#仅用支持向量预测分类</span></span><br><span class="line">		predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b</span><br><span class="line">		<span class="comment">#预测分类结果与标签不符则错误计数加一</span></span><br><span class="line">		<span class="keyword">if</span> sign(predict) != sign(labelArr[i]): errorCount += <span class="number">1</span></span><br><span class="line">	<span class="comment">#打印输出分类错误率</span></span><br><span class="line">	print(<span class="string">"the test error rate is: %f"</span> % (float(errorCount)/m))</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;上述代码分别在训练集和测试集上进行性能测试，打印输出如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>reload(svmMLiA)</span><br><span class="line">&lt;module <span class="string">'svmMLiA'</span> <span class="keyword">from</span> <span class="string">'E:\\机器学习实战\\mycode\\Ch06\\svmMLiA.py'</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>svmMLiA.testRbf()</span><br><span class="line">L==H</span><br><span class="line">fullSet, iter: <span class="number">0</span> i: <span class="number">0</span>, pairs changed <span class="number">0</span></span><br><span class="line">fullSet, iter: <span class="number">0</span> i: <span class="number">1</span>, pairs changed <span class="number">1</span></span><br><span class="line">fullSet, iter: <span class="number">0</span> i: <span class="number">2</span>, pairs changed <span class="number">2</span></span><br><span class="line">fullSet, iter: <span class="number">0</span> i: <span class="number">3</span>, pairs changed <span class="number">3</span></span><br><span class="line">···</span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">96</span>, pairs changed <span class="number">0</span></span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">97</span>, pairs changed <span class="number">0</span></span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">98</span>, pairs changed <span class="number">0</span></span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">99</span>, pairs changed <span class="number">0</span></span><br><span class="line">iteration number: <span class="number">7</span></span><br><span class="line">there are <span class="number">27</span> Support Vectors</span><br><span class="line">the training error rate <span class="keyword">is</span>: <span class="number">0.030000</span></span><br><span class="line">the test error rate <span class="keyword">is</span>: <span class="number">0.040000</span></span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;当然，大家也可以尝试更换不同的k1参数以观察测试错误率、训练错误率、支持向量个数随k1的变化情况。下面个两张图是书上的举例。</p>
<p></p><br><div align="center"><img src="http://img.blog.csdn.net/20171009221909966?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast"></div><br><p></p>

<p></p><br><div align="center"><img src="http://img.blog.csdn.net/20171009221934280?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3NTIxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast"></div><br><p></p>

<p>&emsp;&emsp;我们会发现，支持向量的数目存在一个最优值。SVM的优点在于它能对数据进行高效分类。如果支持向量太少，就可能会得到一个很差的决策边界；如果支持向量太多，也就是相当于每次都利用整个数据集进行分类，这种分类方法成为kNN（多么熟悉）。</p>
<h2 id="手写识别问题回顾"><a href="#手写识别问题回顾" class="headerlink" title="手写识别问题回顾"></a>手写识别问题回顾</h2><p>&emsp;&emsp;SVM对kNN的优点在于，SVM只需要保留支持向量就可以获得可比的效果，占用内存大大减小。下面，我们就用SVM来对手写数字进行分类识别（不加修改的SVM只能用于二分类问题，在这里，我们规定，如果是数字9，则为-1，否则为+1）。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">img2vector</span><span class="params">(filename)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	32*32图像转换为1*1024向量</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		filename：文件名称字符串</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	returnVect：转换之后的1*1024向量</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#初始化要返回的1*1024向量</span></span><br><span class="line">	returnVect = zeros((<span class="number">1</span>, <span class="number">1024</span>))</span><br><span class="line">	<span class="comment">#打开文件</span></span><br><span class="line">	fr = open(filename)</span><br><span class="line">	<span class="comment">#读取文件信息</span></span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">32</span>):</span><br><span class="line">		<span class="comment">#循环读取文件的前32行</span></span><br><span class="line">		lineStr = fr.readline()</span><br><span class="line">		<span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">32</span>):</span><br><span class="line">			<span class="comment">#将每行的头32个字符存储到要返回的向量中</span></span><br><span class="line">			returnVect[<span class="number">0</span>, <span class="number">32</span>*i+j] = int(lineStr[j])</span><br><span class="line">	<span class="comment">#返回要输出的1*1024向量</span></span><br><span class="line">	<span class="keyword">return</span> returnVect</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">loadImages</span><span class="params">(dirName)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	加载图片</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		dirName：文件路径</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	trainingMat：训练数据集</span></span><br><span class="line"><span class="string">				hwLabels：数据标签</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="keyword">from</span> os <span class="keyword">import</span> listdir</span><br><span class="line">	<span class="comment">#初始化数据标签</span></span><br><span class="line">	hwLabels = []</span><br><span class="line">	<span class="comment">#读取文件列表</span></span><br><span class="line">	trainingFileList = listdir(dirName)</span><br><span class="line">	<span class="comment">#读取文件个数</span></span><br><span class="line">	m = len(trainingFileList)</span><br><span class="line">	<span class="comment">#初始化训练数据集</span></span><br><span class="line">	trainingMat = zeros((m,<span class="number">1024</span>))</span><br><span class="line">	<span class="comment">#填充数据集</span></span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> range(m):</span><br><span class="line">		<span class="comment">#遍历所有文件</span></span><br><span class="line">		fileNameStr = trainingFileList[i]</span><br><span class="line">		<span class="comment">#提取文件名称</span></span><br><span class="line">		fileStr = fileNameStr.split(<span class="string">'.'</span>)[<span class="number">0</span>]</span><br><span class="line">		<span class="comment">#提取数字标识</span></span><br><span class="line">		classNumStr = int(fileStr.split(<span class="string">'_'</span>)[<span class="number">0</span>])</span><br><span class="line">		<span class="comment">#数字9记为-1类</span></span><br><span class="line">		<span class="keyword">if</span> classNumStr == <span class="number">9</span>: hwLabels.append(<span class="number">-1</span>)</span><br><span class="line">		<span class="comment">#其他数字记为+1类</span></span><br><span class="line">		<span class="keyword">else</span>: hwLabels.append(<span class="number">1</span>)</span><br><span class="line">		<span class="comment">#提取图像向量，填充数据集</span></span><br><span class="line">		trainingMat[i,:] = img2vector(<span class="string">'%s/%s'</span> % (dirName, fileNameStr))</span><br><span class="line">	<span class="comment">#返回数据集和数据标签</span></span><br><span class="line">	<span class="keyword">return</span> trainingMat, hwLabels</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">testDigits</span><span class="params">(kTup = <span class="params">(<span class="string">'rbf'</span>,<span class="number">10</span>)</span>)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Function：	手写数字分类函数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Input：		kTup：核函数采用径向基函数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	Output：	输出打印信息</span></span><br><span class="line"><span class="string">	"""</span>	</span><br><span class="line">	<span class="comment">#导入数据集</span></span><br><span class="line">	dataArr, labelArr = loadImages(<span class="string">'trainingDigits'</span>)</span><br><span class="line">	<span class="comment">#调用Platt SMO算法</span></span><br><span class="line">	b, alphas = smoPK(dataArr, labelArr, <span class="number">200</span>, <span class="number">0.0001</span>, <span class="number">10000</span>, kTup)</span><br><span class="line">	<span class="comment">#初始化数据矩阵和标签向量</span></span><br><span class="line">	datMat = mat(dataArr); labelMat = mat(labelArr).transpose()</span><br><span class="line">	<span class="comment">#记录支持向量序号</span></span><br><span class="line">	svInd = nonzero(alphas.A &gt; <span class="number">0</span>)[<span class="number">0</span>]</span><br><span class="line">	<span class="comment">#读取支持向量</span></span><br><span class="line">	sVs = datMat[svInd]</span><br><span class="line">	<span class="comment">#读取支持向量对应标签</span></span><br><span class="line">	labelSV = labelMat[svInd]</span><br><span class="line">	<span class="comment">#输出打印信息</span></span><br><span class="line">	print(<span class="string">"there are %d Support Vectors"</span> % shape(sVs)[<span class="number">0</span>])</span><br><span class="line">	<span class="comment">#获取数据集行列值</span></span><br><span class="line">	m, n = shape(datMat)</span><br><span class="line">	<span class="comment">#初始化误差计数</span></span><br><span class="line">	errorCount = <span class="number">0</span></span><br><span class="line">	<span class="comment">#遍历每一行，利用核函数对训练集进行分类</span></span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> range(m):</span><br><span class="line">		<span class="comment">#利用核函数转换数据</span></span><br><span class="line">		kernelEval = kernelTrans(sVs,datMat[i,:],kTup)</span><br><span class="line">		<span class="comment">#仅用支持向量预测分类</span></span><br><span class="line">		predict=kernelEval.T * multiply(labelSV,alphas[svInd]) + b</span><br><span class="line">		<span class="comment">#预测分类结果与标签不符则错误计数加一</span></span><br><span class="line">		<span class="keyword">if</span> sign(predict)!=sign(labelArr[i]): errorCount += <span class="number">1</span></span><br><span class="line">	<span class="comment">#打印输出分类错误率</span></span><br><span class="line">	<span class="keyword">print</span> <span class="string">"the training error rate is: %f"</span> % (float(errorCount)/m)</span><br><span class="line">	<span class="comment">#导入测试数据集</span></span><br><span class="line">	dataArr,labelArr = loadImages(<span class="string">'testDigits'</span>)</span><br><span class="line">	<span class="comment">#初始化误差计数</span></span><br><span class="line">	errorCount = <span class="number">0</span></span><br><span class="line">	<span class="comment">#初始化数据矩阵和标签向量</span></span><br><span class="line">	datMat=mat(dataArr); labelMat = mat(labelArr).transpose()</span><br><span class="line">	<span class="comment">#获取数据集行列值</span></span><br><span class="line">	m,n = shape(datMat)</span><br><span class="line">	<span class="comment">#遍历每一行，利用核函数对测试集进行分类</span></span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> range(m):</span><br><span class="line">		<span class="comment">#利用核函数转换数据</span></span><br><span class="line">		kernelEval = kernelTrans(sVs,datMat[i,:],kTup)</span><br><span class="line">		<span class="comment">#仅用支持向量预测分类</span></span><br><span class="line">		predict=kernelEval.T * multiply(labelSV,alphas[svInd]) + b</span><br><span class="line">		<span class="comment">#预测分类结果与标签不符则错误计数加一</span></span><br><span class="line">		<span class="keyword">if</span> sign(predict)!=sign(labelArr[i]): errorCount += <span class="number">1</span></span><br><span class="line">	<span class="comment">#打印输出分类错误率</span></span><br><span class="line">	<span class="keyword">print</span> <span class="string">"the test error rate is: %f"</span> % (float(errorCount)/m)</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;上面的大部分代码我们都已经很熟悉了，这里就不再赘述，直接进行测试。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>reload(svmMLiA)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>svmMLiA.testDigits((<span class="string">'rbf'</span>, <span class="number">20</span>))</span><br><span class="line">L==H</span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">398</span>, pairs changed <span class="number">0</span></span><br><span class="line">j <span class="keyword">not</span> moving enough</span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">399</span>, pairs changed <span class="number">0</span></span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">400</span>, pairs changed <span class="number">0</span></span><br><span class="line">j <span class="keyword">not</span> moving enough</span><br><span class="line">fullSet, iter: <span class="number">6</span> i: <span class="number">401</span>, pairs changed <span class="number">0</span></span><br><span class="line">iteration number: <span class="number">7</span></span><br><span class="line">there are <span class="number">58</span> Support Vectors</span><br><span class="line">the training error rate <span class="keyword">is</span>: <span class="number">0.000000</span></span><br><span class="line">the test error rate <span class="keyword">is</span>: <span class="number">0.021505</span></span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;尝试不同的σ，并尝试了线性核函数，总结得到如图结果：</p>
<table>
<thead>
<tr>
<th>Kernel,settings</th>
<th>Training error (%)</th>
<th>Test error (%)</th>
<th># Support vectors</th>
</tr>
</thead>
<tbody>
<tr>
<td>RBF,0.1</td>
<td>0</td>
<td>52</td>
<td>402</td>
</tr>
<tr>
<td>RBF,5</td>
<td>0</td>
<td>3.2</td>
<td>402</td>
</tr>
<tr>
<td>RBF,10</td>
<td>0</td>
<td>0.5</td>
<td>99</td>
</tr>
<tr>
<td>RBF,50</td>
<td>0.2</td>
<td>2.2</td>
<td>41</td>
</tr>
<tr>
<td>RBF,100</td>
<td>1.5</td>
<td>4.3</td>
<td>26</td>
</tr>
<tr>
<td>Linear</td>
<td>2.7</td>
<td>2.2</td>
<td>28</td>
</tr>
</tbody>
</table>
<p>&emsp;&emsp;结果表明，当径向基函数的参数σ取10左右时，就可以得到最小的测试错误率。同时，最小的训练错误率，并不对应于最小的支持向量数目。另外，线性核函数的效果并不是特别糟糕，可以以牺牲线性核函数的错误率来换取分类速度的提高。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>&emsp;&emsp;支持向量机是一种分类器。之所以称为“机”是因为它会产生一个二值决策结果，即它是一种决策“机”。支持向量机的泛化错误率较低，具有良好的学习能力，且学到的结果具有很好的推广性。这些优点使得支持向量机十分流行，有些人认为他是监督学习中最好的定式算法。</p>
<p><strong><font color="red" size="3" face="仿宋">系列教程持续发布中，欢迎订阅、关注、收藏、评论、点赞哦～～(￣▽￣～)～</font></strong></p>
<p><strong><font color="red" size="3" face="仿宋">完的汪(∪｡∪)｡｡｡zzz</font></strong></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Word Zzzz
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://wordzzzz.gitee.io/2017/11/05/ml-17/" title="《机器学习实战》之支持向量机（4）核函数及其实现">http://wordzzzz.gitee.io/2017/11/05/ml-17/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ML/" rel="tag"># ML</a>
          
            <a href="/tags/python3/" rel="tag"># python3</a>
          
            <a href="/tags/SVM/" rel="tag"># SVM</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/11/05/ml-15/" rel="next" title="《机器学习实战》之支持向量机（2）简化版SMO">
                <i class="fa fa-chevron-left"></i> 《机器学习实战》之支持向量机（2）简化版SMO
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/05/ml-16/" rel="prev" title="《机器学习实战》之支持向量机（3）完整版SMO">
                《机器学习实战》之支持向量机（3）完整版SMO <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjgzNi85Mzk3"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Word Zzzz" />
            
              <p class="site-author-name" itemprop="name">Word Zzzz</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

			<!--my custom code begin-->
			<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
			<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js"></script>
			<script type="text/javascript">
			  $("#sidebar").hover(function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 1});
			  },function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 0});
			  });
			</script>
			<div id="mydivshow" class="mydivshow">
			<!--my custom code end-->
			
          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">155</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/wordzzzz" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/wordzzzz" target="_blank" title="Gitee">
                    
                      <i class="fa fa-fw fa-glide"></i>Gitee</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:wordzzzzgm@gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://plus.google.com/" target="_blank" title="Google">
                    
                      <i class="fa fa-fw fa-google"></i>Google</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.weibo.com/u/3191972527?from=107C295010&wm=20005_0002&sourceType=weixin&uid=3191972527&is_all=1" target="_blank" title="微博">
                    
                      <i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wordzzzz" target="_blank" title="知乎">
                    
                      <i class="fa fa-fw fa-bell"></i>知乎</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/u011475210" title="CSDN博客主页" target="_blank">CSDN博客主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.gitee.io" title="中国站主页" target="_blank">中国站主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.github.io" title="全球站主页" target="_blank">全球站主页</a>
                  </li>
                
              </ul>
            </div>
          

          <div id="player1" class="aplayer"></div>
<script src="/js/src/APlayer.min.js"></script>
<script type="text/javascript">
var ap = new APlayer({
    element: document.getElementById('player1'),                       // Optional, player element
    narrow: false,                                                     // Optional, narrow style
    autoplay: false,                                                    // Optional, autoplay song(s), not supported by mobile browsers
    showlrc: 0,                                                        // Optional, show lrc, can be 0, 1, 2, see: ###With lrc
    mutex: true,                                                       // Optional, pause other players when this player playing
    theme: '#e6d0b2',                                                  // Optional, theme color, default: #b7daff
    mode: 'random',                                                    // Optional, play mode, can be `random` `single` `circulation`(loop) `order`(no loop), default: `circulation`
    preload: 'metadata',                                               // Optional, the way to load music, can be 'none' 'metadata' 'auto', default: 'auto'
    listmaxheight: '513px',                                             // Optional, max height of play list
    music: {                                                           // Required, music info, see: ###With playlist
        title: '你曾是少年',                                          // Required, music title
        author: 'cover',                          // Required, music author
        url: 'http://mp3.qqmusic.cc/yq/102426570.mp3',  // Required, music url
        pic: '/images/visitor.jpg',  // Optional, music picture
    }
});
</script>
        </div>
		<!--my custom code begin-->
		</div>
		<!--my custom code end-->
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言："><span class="nav-number">1.</span> <span class="nav-text">前言：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#核函数简介"><span class="nav-number">2.</span> <span class="nav-text">核函数简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#径向基函数"><span class="nav-number">3.</span> <span class="nav-text">径向基函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#核函数实现"><span class="nav-number">4.</span> <span class="nav-text">核函数实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#手写识别问题回顾"><span class="nav-number">5.</span> <span class="nav-text">手写识别问题回顾</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Word Zzzz</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">176.8k</span>
  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>




  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("tnjOBN3eibs4dfP2s8dFMF8s-gzGzoHsz", "tDaBF4vRsSyaeSk9vKOOow6E");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML"></script>
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  <script src="/js/src/Aplayer-Controler.js"></script>
<div id="AP-controler"></div>
<script type="text/javascript">
var myapc=new APlayer_Controler({
		APC_dom:$('#AP-controler'),
		aplayer:ap, //此为绑定的aplayer对象
		attach_right:false,
		position:{top:'300px',bottom:''},
		fixed:true,
		btn_width:100,
		btn_height:120,
		img_src:['http://oty1v077k.bkt.clouddn.com/bukagirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/jumpgirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/pentigirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/%E8%90%8C1.gif'],
		img_style:{repeat:'no-repeat',position:'center',size:'contain'},
		ctrls_color:'rgba(173,255,47,0.8)',
		ctrls_hover_color:'rgba(255,140,0,0.7)',
		tips_on:true,
		tips_width:140,
		tips_height:25,
		tips_color:'rgba(255,255,255,0.6)',
		tips_content:{},
		timeout:30
	});
</script>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>



</body>
</html>
